package com.niit.spark.streaming

import org.apache.spark.SparkConf
import org.apache.spark.streaming.dstream.{DStream, ReceiverInputDStream}
import org.apache.spark.streaming.{Seconds, StreamingContext}

/**
 * Date:2025/5/21
 * Author：Ys
 * Description:
 */
object SparkStreaming06_Window {

  def main(args: Array[String]): Unit = {
    val conf = new SparkConf().setMaster("local[*]").setAppName("SparkStreaming06_Window")
    val ssc = new StreamingContext(conf,Seconds(3))
    ssc.sparkContext.setLogLevel("ERROR")


    val lines: ReceiverInputDStream[String] = ssc.socketTextStream("localhost", 9999)

    val wordOne: DStream[(String, Int)] = lines.flatMap(line => line.split(" ")).map(word => (word, 1))

    /*
      窗口的范围必须是采集周期的整数倍
      第一个参数：窗口的时长 （一次采集几个周期的数据）
      第二个参数：滑块步长（滑动一次采集几个周期的数据）
     */

    val winDS: DStream[(String, Int)] = wordOne.window(Seconds(6), Seconds(6))

    winDS.reduceByKey(_ + _).print()

    ssc.start()

    ssc.awaitTermination()
  }

}
